import React from 'react';
import {useHistory} from 'react-router-dom';
import {makeStyles ,Typography,TextField,Button } from '@material-ui/core';
import {AccountCircle} from '@material-ui/icons';
import {useFormik } from 'formik';
import * as Yup from 'yup';
import Password from './Password';
const useStyles = makeStyles((theme) => ({
  loginBox: {
    '& > div': {
      marginBottom:'15px'
    },
  },
  error: {
    padding:0,
    color: 'red',
    textAlign:'left',
    fontSize:'12px',
    margin:0,
    paddingLeft:'1.4rem'
  }
}));
const styleProps = {
  width:'400px'
};
export default function Login() {
  const history = useHistory();
  const classes = useStyles();
  //构造和验证数据
  const formik = useFormik({
    initialValues: {
      username:'',
      password:''
    },
    validate: values => {
      const errors = {};
      if(!values.username) {
        errors.username = '请输入用户名'
      }
      if(!values.password) {
        errors.password ='请输入密码'
      }
      return errors;
    },
    validationSchema: Yup.object({
      username: Yup.string()
        .min(3,'用户名不能短于3个字符').max(20,'用户名不能长于15个字符'),
      password: Yup.string()
        
    }),
    onSubmit: values => {
      console.log(values);
      localStorage.setItem('token',1);
      localStorage.setItem('user',values.username);
      history.push('/home')
    } 
  });
  //模拟登录
  const {setFieldValue,setFieldTouched} = formik;
  return (
    
    <div style={{width:'100%',height:'100vh'}}>
      
        <div className={classes.loginBox} style={{width:'444px',margin:'150px auto',textAlign:'center'}}>
          <div>
            <AccountCircle style={{color:'rgb(220, 0, 78)',fontSize:'40px'}}  />
          </div>
          <div>
            <Typography variant='h4'>Login</Typography>
          </div>
          <div>
            <TextField style={styleProps} id="username" label="Login Name *" variant="outlined" value={formik.values.username} onChange={formik.handleChange} onBlur={formik.handleBlur} />
            {(formik.touched.username && formik.errors.username) && <p className={classes.error}>{formik.errors.username}</p>}
          </div>
          <Password styleProps={styleProps} value={formik.values.password} touched={formik.touched.password} errors={formik.errors} setFieldValue={setFieldValue}  />
          <div>
            <Button style={styleProps} variant="contained" color="secondary" onClick={formik.handleSubmit}>
              Login
            </Button>
          </div>
        </div>
      
    </div>
  )
}
